package com.fa4j.third.file.local.adapter;

import com.fa4j.common.base.exception.CommonRequestError;
import com.fa4j.third.base.adapter.AbstractThirdServiceAdapter;
import com.fa4j.third.file.model.*;
import com.fa4j.third.file.service.ThirdFileService;
import lombok.Setter;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.FileSystemUtils;

import java.io.*;

@Slf4j
@Setter
public class LocalFileServiceAdapter extends AbstractThirdServiceAdapter implements ThirdFileService {

    private String urlPrefix;
    private String localDir;
    private Long maxFileSize;
    private String fileTypes;

    /**
     * 初始化
     */
    @Override
    public void init() {
        super.init();
        localDir = localDir.replaceFirst("~", System.getProperty("user.home"));
    }

    @Override
    public void close() throws IOException {
        super.close();
        log.info("LocalFileServiceAdapter close...");
    }

    @Override
    @SneakyThrows
    public void upload(ThirdFileUploadCmd cmd, InputStream inputStream) {
        if (cmd.getFileSize() > maxFileSize) {
            //操过文件大小
            throw ThirdFileError.MAX_SIZE_LIMITED.build(cmd.getFileSize() / 1204 + "kb");
        }
        if (!fileTypes.contains(cmd.getFileExtension().toLowerCase())) {
            throw ThirdFileError.NOT_SUPPORT_FILE_TYPE.build();
        }
        File file = getLocalFile(cmd.getFilePath());

        if (!file.exists()) {
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            file.createNewFile();
        }
        FileCopyUtils.copy(inputStream, new FileOutputStream(file));

    }

    private File getLocalFile(String filePath) {
        String localFile = localDir + getProps().getBizCode() + filePath;
        return new File(localFile);
    }

    @Override
    public void remove(ThirdFileRemoveCmd cmd) {
        File file = getLocalFile(cmd.getFilePath());
        if (file.exists()) {
            FileSystemUtils.deleteRecursively(file);
        }
    }

    @Override
    @SneakyThrows
    public void download(ThirdFileDownloadCmd cmd, OutputStream outputStream) {
        File file = getLocalFile(cmd.getFilePath());
        if (!file.exists()) {
            throw CommonRequestError.NOT_FOUND.build("文件");
        }
        FileCopyUtils.copy(new FileInputStream(file), outputStream);
    }

    @Override
    public String getFileUrl(ThirdFileUrlCmd cmd) {
        return urlPrefix + getProps().getBizCode() + cmd.getFilePath();
    }
}
